package com.lxd.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.lxd.entity.TokenUserInfoDto;
import com.lxd.entity.po.Activity;
import com.lxd.entity.query.ActivityQuery;
import com.lxd.exception.BusinessException;
import com.lxd.mappers.ActivityMapper;
import com.lxd.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.lxd.entity.enums.PageSize;
import com.lxd.entity.query.FileQuery;
import com.lxd.entity.po.File;
import com.lxd.entity.vo.PaginationResultVO;
import com.lxd.entity.query.SimplePage;
import com.lxd.mappers.FileMapper;
import com.lxd.service.FileService;
import com.lxd.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 文件表 业务接口实现
 */
@Service("fileService")
public class FileServiceImpl implements FileService {

    @Resource
    private FileMapper<File, FileQuery> fileMapper;
    @Resource
    private ActivityMapper<Activity, ActivityQuery> activityMapper;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.base-url}")
    private String baseUrl;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<File> findListByParam(FileQuery param) {
        return this.fileMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(FileQuery param) {
        return this.fileMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<File> findListByPage(FileQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<File> list = this.findListByParam(param);
        PaginationResultVO<File> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(File bean) {
        return this.fileMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<File> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.fileMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<File> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.fileMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(File bean, FileQuery param) {
        StringTools.checkParam(param);
        return this.fileMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(FileQuery param) {
        StringTools.checkParam(param);
        return this.fileMapper.deleteByParam(param);
    }

    /**
     * 根据Id获取对象
     */
    @Override
    public File getFileById(Long id) {
        return this.fileMapper.selectById(id);
    }

    /**
     * 根据Id修改
     */
    @Override
    public Integer updateFileById(File bean, Long id) {
        return this.fileMapper.updateById(bean, id);
    }

    /**
     * 根据Id删除
     */
    @Override
    public Integer deleteFileById(Long id) {
        return this.fileMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void upload(MultipartFile multipartFile, Integer relateType, Integer relateId,TokenUserInfoDto tokenUserInfoDto) {
//         生成文件存储路径
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String uploadPath = uploadDir + "/" + datePath;

        // 创建目录
        java.io.File dir = new java.io.File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = multipartFile.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;
        //获取文件类型
        String fileType = multipartFile.getContentType();
        // 完整的文件路径
        String filePath = uploadPath + "/" + fileName;

        // 保存文件
        try {
            multipartFile.transferTo(new  java.io.File(filePath));
        } catch (IOException e) {
            throw new BusinessException(e);
        }

        // 生成访问URL
        String fileUrl = baseUrl + datePath + "/" + fileName;
        File fileEntity = new File();
        fileEntity.setFileName(originalFilename);
        fileEntity.setFilePath(fileUrl);
        fileEntity.setFileSize(multipartFile.getSize());
        fileEntity.setRelatedType(relateType);
        fileEntity.setRelatedId(Long.valueOf(relateId));
        fileEntity.setUploadedBy(Long.valueOf(tokenUserInfoDto.getUserId()));
        fileEntity.setUploadedAt(new Date());
        fileEntity.setFileType(fileType);

        fileMapper.insert(fileEntity);
    }

    @Override
    public PaginationResultVO<File> getFileList(FileQuery param) {
        //查询文件总数
        int count = fileMapper.selectCount(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);

        List<File> files = fileMapper.selectList(param);
        return new PaginationResultVO<>(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), files);
    }

    @Override
    public List<String> getLatestImages(int limit) {
        FileQuery query = new FileQuery();
        query.setPageSize(limit);
        query.setPageNo(1);
        // 只查询图片类型的文件
//        query.setFileType("image/%");  // 使用模糊匹配查询所有图片类型

        SimplePage page = new SimplePage(query.getPageNo(), 999, query.getPageSize());
        query.setSimplePage(page);

        List<File> files = fileMapper.selectList(query);
        return files.stream()
                .map(File::getFilePath)
                .collect(Collectors.toList());
    }

    /**
     * 删除文件
     */
    @Override
    public void deleteFile(Long id) {
        // 获取文件信息
        File file = fileMapper.selectById(id);
        if (file != null) {
            // 删除物理文件
            java.io.File physicalFile = new java.io.File(file.getFilePath());
            if (physicalFile.exists()) {
                physicalFile.delete();
            }

            // 删除数据库记录
            fileMapper.deleteById(id);
        }
    }

    @Override
    public List<String> getImagesByRelatedId(Long relatedId, Integer relatedType) {
        FileQuery query = new FileQuery();
        query.setRelatedId(relatedId);
        query.setRelatedType(relatedType);

        List<File> files = fileMapper.selectList(query);
        return files.stream()
                .map(File::getFilePath)
                .collect(Collectors.toList());
    }

    @Override
    public String getLatestImageByRelatedId(Long relatedId, Integer relatedType) {
        File file = fileMapper.selectLatestByRelatedId(relatedId, relatedType);
        return file != null ? file.getFilePath() : null;
    }
}